package com.wrial.kind.doublepointer;
/*
 * @Author  Wrial
 * @Date Created in 15:20 2020/8/7
 * @Description
 */

public class LinkedListHasCycle {

    /**
     * 使用快慢指针，快指针每次走两个，慢指针一次走一个
     *
     * @param head
     * @return
     */
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode fast = dummy.next.next;
        ListNode slow = dummy.next;
        while (fast != null) {
            if (fast == slow) {
                return true;
            }
            if (fast.next != null) {
                fast = fast.next.next;
                slow = slow.next;
            } else {
                return false;
            }
        }
        return false;
    }

    class ListNode {
        ListNode(int val) {
            this.val = val;
        }

        int val;
        ListNode next;
    }
}